package com.liuchuanzheng.lcz_wanandroid.module.home.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.liuchuanzheng.lcz_wanandroid.R
import com.liuchuanzheng.lcz_wanandroid.base.BaseVMFragment
import com.liuchuanzheng.lcz_wanandroid.databinding.FragmentProjectsBinding
import com.liuchuanzheng.lcz_wanandroid.module.common.bus.CollectStatusEvent
import com.liuchuanzheng.lcz_wanandroid.module.common.callback.EmptyCallback
import com.liuchuanzheng.lcz_wanandroid.module.common.callback.ErrorCallback
import com.liuchuanzheng.lcz_wanandroid.module.common.callback.LoadingCallback
import com.liuchuanzheng.lcz_wanandroid.module.detail.activity.DetailWebActivity
import com.liuchuanzheng.lcz_wanandroid.module.home.adapter.ArticleAdapter
import com.liuchuanzheng.lcz_wanandroid.module.home.adapter.ProjectAdapter
import com.liuchuanzheng.lcz_wanandroid.module.home.viewmodel.LatestProjectsViewModel
import com.liuchuanzheng.lcz_wanandroid.module.user.UserManager
import com.liuchuanzheng.lcz_wanandroid.module.user.activity.LoginActivity
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

/**
 * @author 刘传政
 * @date 2021/9/14 0014 17:24
 * QQ:1052374416
 * 电话:18501231486
 * 作用:最新项目列表
 * 注意事项:
 */
class LatestProjectsFragment: BaseVMFragment<LatestProjectsViewModel>() {
    lateinit var mViewBinding:FragmentProjectsBinding
    val adapter: ProjectAdapter by lazy { ProjectAdapter() }
    lateinit var loadService: LoadService<Any>
    /**
     * 当页面可见的时候，才加载当前页面。 没有打开的页面，就不会预加载。
     *
     *
     * 说白了，懒加载就是可见的时候才去请求数据。
     * 只回调一次
     */
    override fun onLazyLoad() {
        mViewModel.getLatestProjects(true)
    }

    /**
     * 因为系统自带的设置view方法有很多种,id,view都可以.所以这里不像
     * 大家都用id的封装方式,那是限制了自己
     * @param inflater
     * @param container
     */
    override fun creatView(inflater: LayoutInflater?, container: ViewGroup?): View {
        mViewBinding = FragmentProjectsBinding.inflate(inflater!!, container, false)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadService = LoadSir.getDefault().register(
            mViewBinding.smartRefreshLayout,
            Callback.OnReloadListener {
                loadService.showCallback(LoadingCallback::class.java)
                mViewModel.getLatestProjects(true)
            })
        mViewBinding.smartRefreshLayout.setEnableRefresh(true)
        mViewBinding.smartRefreshLayout.setEnableLoadMore(true)
        mViewBinding.smartRefreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                mViewModel.getLatestProjects(true)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewModel.getLatestProjects(false)
            }

        })
        mViewBinding.recyclerView.setLayoutManager(LinearLayoutManager(activity))
        mViewBinding.recyclerView.adapter = adapter
        adapter.setOnItemClickListener { adapter, view, position ->
            DetailWebActivity.start(requireContext(),this@LatestProjectsFragment.adapter.getItem(position) )
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.iv_collect) {
                if (UserManager.isLogin()) {
                    var article = this@LatestProjectsFragment.adapter.data[position]
                    if (article.collect) {
                        mViewModel.uncollect(article.id)
                    }else{
                        mViewModel.collect(article.id)
                    }
                }else{
                    LoginActivity.start(requireActivity())
                }

            }
        }
        LiveEventBus
            .get(CollectStatusEvent::class.java)
            .observe(this, Observer { event->
                val item = adapter.data.find { it.id == event.id }
                if (item != null) {
                    item.collect = event.collect
                    adapter.notifyDataSetChanged()
                }

            })
    }

    /**
     * 进行观察订阅
     */
    override fun observeViewModel() {
        mViewModel.projectList.observe(this,{
            if (it.isRefresh) {
                //刷新的结果
                adapter.setList(it.dataList)

            }else{
                //加载更多的结果
                adapter.addData(it.dataList!!)
            }
        })
        mViewModel.smartRefreshStatus.observe(this,{
            if (it) {
                //基本不会触发到
                mViewBinding.smartRefreshLayout.autoRefreshAnimationOnly()
            }else{
                mViewBinding.smartRefreshLayout.finishRefresh()
            }
        })
        mViewModel.smartLoaMoreStatus.observe(this,{
            if (it) {
                //基本不会触发到
                mViewBinding.smartRefreshLayout.autoLoadMoreAnimationOnly()
            }else{
                mViewBinding.smartRefreshLayout.finishLoadMore()
            }
        })
        mViewModel.liveData_loadServiceStatus.observe(this,{
            //loadsir的状态 1 empty 2 error 3 loading
            if (adapter.data.isNullOrEmpty()) {
                if (it is ErrorCallback) {
                    loadService.showCallback(ErrorCallback::class.java)
                }else if (it is SuccessCallback){
                    loadService.showCallback(EmptyCallback::class.java)
                }
            }else{
                loadService.showSuccess()
            }

        })
        mViewModel.liveData_loading.observe(this,{
            if (it) {
                showLoading("加载中")
            }else{
                hideLoading()
            }

        })

    }
}